const jsonApi = require('utils/jsonapi-datastore/dist/jsonapi-datastore.js')


App({
  data: {
    info: '',
    mp_id: 'd8d49a5800362843f29833e03038a72a',
  },
  onLaunch: function () {
    // 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
    // 调用API从本地缓存中获取数据
    var that = this
    this.store = new (jsonApi.JsonApiDataStore)
    this.jsonModel = jsonApi.JsonApiDataStoreModel
    this.checkLogin()
  },

  checkLogin: function (cb) {
    
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      var that = this
      wx.checkSession({
        success: function (res) {
          var session_3rd = wx.getStorageSync('session_3rd')
          //登录态未过期
            wx.request({
              url: `${that.globalData.DOMAIN}/mpbase/wxapp/checkSession`,
              data: {
                session_3rd: session_3rd
              },
              method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
              // header: {}, // 设置请求的 header
              success: function (res) {
                console.log(res)
                if(!res.data){
                  that.loginUct()
                }
              },
              fail: function () {
                // fail
              },
              complete: function () {
                // complete
              }
            })
          

        },
        fail: function (res) {
          //登录态过期
          that.loginUct();
        }
      })

    }
  },
  //登录函数
  loginUct: function () {
    console.log('login')
    var that = this;
    //调用登录接口
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求，通过jscode获取session
          wx.request({
            url: `${that.globalData.DOMAIN}/mpbase/wxapp/onLogin`,
            data: {
              mp_id: getApp().data.mp_id,
              code: res.code
            },
            success: function (res) {
              console.log(res.data)
              wx.setStorageSync("session_3rd", res.data.session_3rd);
            }
          })
          wx.getUserInfo({
            success: function (res) {
              console.log(res)
              var userInfo = res.userInfo
              var session_3rd = wx.getStorageSync('session_3rd')
              console.log(session_3rd)
              wx.request({
                url: `${that.globalData.DOMAIN}/mpbase/wxapp/setUserInfo`,
                data: {
                  mp_id: getApp().data.mp_id,
                  userInfo: userInfo,
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                  rawData: res.rawData,
                  signature: res.signature,
                  session_3rd: session_3rd
                },
                method: 'POST',
                success: function (res) {
                  console.log(res)
                },
                fail: function () {
                  // fail
                },
                complete: function () {
                  // complete
                }
              })
              //加密，在请求的时候携带
              that.globalData.encrypted = { encryptedData: res.encryptedData, iv: res.iv }
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
  },

  request: function (obj) {
    var header = obj.header || {}
    if (!header['Content-Type']) {
      header['Content-Type'] = 'application/json'
    }
    if (!header['Authorization']) {
      header['Authorization'] = this.globalData.token
    }

    // This must be wx.request !
    wx.request({
      url: obj.url,
      data: obj.data || {},
      method: obj.method || 'GET',
      header: header,
      success: function (res) {
        typeof obj.success == "function" && obj.success(res)
      },
      fail: obj.fail || function () { },
      complete: obj.complete || function () { }
    })
  },

  authRequest: function (obj) {
    var that = this
    if (!that.globalData.token) {
      var token = wx.getStorageSync('userToken')
      if (!token) {
        wx.hideToast()
        wx.showModal({
          title: '未登录',
          content: '请前往 “我的” 页面绑定手机号',
          showCancel: false,
          success: function (res) {
            // 清除没用的token
            wx.removeStorage({ key: 'userToken' })
            that.globalData.token = undefined
            if (getCurrentPages().length > 1) {
              wx.navigateBack()
            }
          }
        })
        return
      }
      that.globalData.token = token
      that.request({
        url: `${that.globalData.API_URL}/sessions/new`,
        data: { code: that.globalData.code },
        success: function (res) {
          if (!res.data.token) {
            wx.showModal({
              title: '未登录',
              content: '请前往 “我的” 页面绑定手机号',
              showCancel: false,
              success: function (res) {
                // 清除没用的token
                wx.removeStorage({ key: 'userToken' })
                that.globalData.token = undefined
                if (getCurrentPages().length > 1) {
                  wx.navigateBack()
                }
              }
            })
          } else {
            that.globalData.currentCustomer = res.data.customer
            that.globalData.token = res.data.token
            wx.setStorage({
              key: 'userToken',
              data: res.data.token
            })
            that.request(obj)
          }
        },
        fail: function (res) { }
      })
    } else {
      that.request(obj)
    }
  },

  globalData: {
    featureManager: {},
    userInfo: null,
    currentCustomer: null,
    API_URL: 'https://www.huaict.com/api',
    DOMAIN: 'https://www.huaict.com'
  }
})
